import getOSSParams from "./getOssParam";

class OSSClient {
  client: null | any = null;
  host = "";
  constructor() {
    this.init();
  }
  loadCDN() {
    if (document.querySelector("#oss-cdn")) return;
    const src = "https://gosspublic.alicdn.com/aliyun-oss-sdk-6.15.0.min.js";
    const dom = window.document.createElement("script");
    dom.id = "oss-cdn";
    dom.type = "text/javascript";
    dom.src = src;
    document.getElementsByTagName("head")[0].append(dom);
    return new Promise(r => {
      dom.onload = () => {
        r(true);
      };
    });
  }
  async init() {
    await this.loadCDN();
    const [res1, res2] = await Promise.all([getOSSParams(), this.loadCDN()]);
    let config = {
      endpoint: "oss-cn-shanghai.aliyuncs.com", // 创建Bucket时会选择不同地区，根据自己的选择填入对应名称
      accessKeyId: res1.result.accessKeyId, // 填入你的accessKeyId
      accessKeySecret: res1.result.accessKeySecret, // 填入你的accessKeySecret
      bucket: res1.result.bucketName, // 填入你的bucket名
      stsToken: res1.result.securityToken
    };
    this.client = new OSS(config);
    this.host = "https://" + config.bucket + "." + this.client.options.endpoint.host + "/";
  }
  async putPhoto(file: File|Blob) {
    const date = new Date().toISOString().substr(0,10)
    const stamp = Date.now()
    const key = `panda/${date}/${stamp}.png`;
    await this.client.put(key, file);
    return this.host + key;
  }
}

export default new OSSClient();
